package com.example.bluetooth;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.lang.reflect.Method;

import static com.example.bluetooth.MainActivity.EXTRA_DEVICE_ADDRESS;

public class BluetoothShowActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 100;
    // 默认当前被选中的item的位置为0
    public static int CURREN_POSITION = 0;
    private ProgressDialog progressDialog; //搜索时显示
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDeviceAdapter mBluetoothDeviceAdapter;
    private BluetoothReceiver mBlueToothReceiver;
    private ListView listView;
    private static String TAG = "BlueTag";
    private Button btn_search;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_show);
        listView = findViewById(R.id.blue_show_lv);
        mBluetoothDeviceAdapter = new BluetoothDeviceAdapter(this);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //获取默认的蓝牙适配器
        btn_search = findViewById(R.id.btn_search);

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查是否支持蓝牙并开启蓝牙
                checkBluetoohStatus();

//                // 让自生能够被扫描到
//                ensureDiscoverable();

                //获取权限，只有获取权限后才可以得到蓝牙的信息
                getBluePermission();
                getPermission();
                // 注册广播
                registerBroadcast();
                // 搜索蓝牙
                searchBluetooth();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 是否在扫描
                if (mBluetoothAdapter.isDiscovering()) {
                    // 取消扫描
                    mBluetoothAdapter.cancelDiscovery();
                }
                try {
                    BluetoothDevice device = mBluetoothDeviceAdapter.getDevice(position);
                    Method createBondMethod;
                    Boolean returnValue = false;
                    if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                        // 反射方法调用；
                        createBondMethod = BluetoothDevice.class.getMethod("createBond");
                        // 与设备建立连接
                        returnValue = (Boolean) createBondMethod.invoke(device);
//                        Log.e("tagE", " 设备位置：" + position);
                        // 更新当前被选中的位置
                        CURREN_POSITION = position;
                        // 刷新 ListView
                        mBluetoothDeviceAdapter.notifyDataSetChanged();
                    } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                        String address = device.getAddress();
                        Log.e("tagE", " 设备名字：" + device.getName() + "   设备地址：" + address);
                        Intent intent = new Intent(BluetoothShowActivity.this, MainActivity.class);
                        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 申请请求许可权限
    private void getBluePermission() {
//        Log.e("tagE", "--申请权限--");
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_CONTACTS)) {
                Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 解决：无法发现蓝牙设备的问题
     * <p>
     * 对于发现新设备这个功能, 还需另外两个权限(Android M 以上版本需要显式获取授权,附授权代码):
     */
    private final int ACCESS_LOCATION = 1;

    @SuppressLint("WrongConstant")
    private void getPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            int permissionCheck = 0;
            permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionCheck += this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                //未获得权限
                this.requestPermissions( // 请求授权
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_LOCATION);// 自定义常量,任意整型
            }
        }
    }

    /**
     * 请求权限的结果回调。每次调用 requestpermissions（string[]，int）时都会调用此方法。
     *
     * @param requestCode  传入的请求代码
     * @param permissions  传入permissions的要求
     * @param grantResults 相应权限的授予结果:PERMISSION_GRANTED 或 PERMISSION_DENIED
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case ACCESS_LOCATION:
                if (hasAllPermissionGranted(grantResults)) {
                    Log.i(TAG, "onRequestPermissionsResult: 用户允许权限");
                } else {
                    Log.i(TAG, "onRequestPermissionsResult: 拒绝搜索设备权限");
                }
                break;
        }
    }

    private boolean hasAllPermissionGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查蓝牙的状态，并开启蓝牙
     */
    private void checkBluetoohStatus() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(BluetoothShowActivity.this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        // 打开蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOn, -1);
        }
//        Log.e(TAG, "startDiscovery: 开启蓝牙");
    }

    /**
     * 让自身可以被发现
     */
    private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //设置本机蓝牙在 300 秒之内可以被 搜索
            startActivity(discoverableIntent);
        }
    }


    /**
     * 注册蓝牙广播
     */
    private void registerBroadcast() {
//        Log.e("tagE", "--注册蓝牙广播--");
        //监听蓝牙开启关闭的广播
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filter);
        //获取蓝牙设备的广播
        IntentFilter mIntentFilter = new IntentFilter();
        // 找到设备的广播
        mIntentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        mIntentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mIntentFilter.setPriority(Integer.MAX_VALUE);
        // 注册广播
        mBlueToothReceiver = new BluetoothReceiver();
        registerReceiver(mBlueToothReceiver, mIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();//解除注册
        Log.e("BSAdapter", " -- onDestroy -- ");
        unregisterReceiver(receiver);
        unregisterReceiver(mBlueToothReceiver);
    }


    /**
     * 搜索蓝牙
     */
    private void searchBluetooth() {
//        Log.e("tagE", "--搜索蓝牙--");
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //清除适配器的内容，以便从新搜索
        mBluetoothDeviceAdapter.clear();
        mBluetoothDeviceAdapter.notifyDataSetChanged();
        // 如果已经在搜索了，那么取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 寻找所有蓝牙设备
        mBluetoothAdapter.startDiscovery();
        //开启进度条
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(BluetoothShowActivity.this);
        }
//        progressDialog.setCanceledOnTouchOutside(false); //实现点击外部不消失。
        progressDialog.setMessage("正在搜索中，请稍候...");
        progressDialog.show();
    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            Log.e("tagE", "--蓝牙开关广播--");
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 1);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    Toast.makeText(BluetoothShowActivity.this, "蓝牙已关闭", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothAdapter.STATE_ON:
                    Toast.makeText(BluetoothShowActivity.this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public class BluetoothReceiver extends BroadcastReceiver {
        //        private String pair_info;
//        private String unpair_info;
        @Override
        public void onReceive(Context context, Intent intent) {
//            Log.e("tagE", "-- 蓝牙搜索广播 --");
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                listView.setAdapter(mBluetoothDeviceAdapter);
                Log.e("设备", device.getName() + " : " + device.getAddress());
                // 将设备放到添加到适配器中
                mBluetoothDeviceAdapter.addDevice(device);
                // 数据改变并更新列表
                mBluetoothDeviceAdapter.notifyDataSetChanged();
//                if( device.getBondState() == BluetoothDevice.BOND_BONDED ) {
//                    pair_info = device.getAddress();
//                }else {
//                    unpair_info = device.getAddress();
//                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                // 关闭进度条
                progressDialog.dismiss();
                Toast.makeText(BluetoothShowActivity.this, "搜索完成", Toast.LENGTH_SHORT).show();
            }
        }
    }


}
